import Header from "@/components/Header";
import Search from "@/components/Search";
import Catorgeries from "@/components/Catorgeries";
import ChannelList from "@/components/ChannelList";
import HotNews from "@/components/HotNews";
import HorizontalNews from "@/components/HorizontalNews";

import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { getNewsList } from "@/api";

import { formatArticleContent } from '@/utils/formatArticleContent' 

import { INews } from "@/types";
// import { useLoaderData } from 'react-router-dom';

const Home = () => {
    // const data = useLoaderData();
    // const newsList = data.data[0].contents.map((i:any) => {
    //     return {
    //         id: i.id,
    //         title: i.title,
    //         date: i.published_at,
    //         author: i.article.editor,
    //         imageUrl: i.article.thumbnail,
    //         content: i.article.origin
    //     }
    // });

    const navigate = useNavigate();

    const [newsList, setNewsList] = useState<INews[]>([]);

    useEffect(() => {
        getNewsList({ pageNum: 1, pageSize: 10 }).then((res:any) => {
            setNewsList(
                res.data[0].contents.map((i: any) => {
                    return {
                        id: i.id,
                        title: i.title,
                        date: i.published_at,
                        author: i.article.editor,
                        imageUrl: i.article.thumbnail,
                        content: formatArticleContent(i.article.origin, i.article.thumbnail, true),
                    };
                })
            );
        });
    }, []);

    const [showChannelList, setShowChannelList] = useState<boolean>(false);
    const onAddChannel = () => {
        setShowChannelList(!showChannelList);
    };
    const onHandleGoToSeeAll = () => {
        navigate("/list");
    };
    return (
        <>
            {/* 顶部用户卡片 */}
            <Header />
            {/* 搜索组件 */}
            <Search />
            {/* 分类组件(channel) */}
            <Catorgeries onAddChannel={onAddChannel} />
            {/* hot news & see all */}
            <HotNews onGoList={onHandleGoToSeeAll} />
            {/* 横向滚动新闻list */}
            <HorizontalNews newList={newsList} />
            {
                // ChannelList 添加更改频道组件
                showChannelList && (
                    <ChannelList
                        show={showChannelList}
                        onHide={() => setShowChannelList(false)}
                    />
                )
            }
        </>
    );
};

export default Home;
